package edu.zju.gis.cky.controller;

import edu.zju.gis.cky.entity.Tile;
import edu.zju.gis.cky.service.TileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @author Zhou Yuquan
 * @version 1.0, 2021-12-29
 */
@RequestMapping("/tile")
@RestController
public class TileController {

    @Autowired
    private TileService tileService;

    @GetMapping("/mvt/{tableName}/{x}/{y}/{z}")
    public void getMvtTile(@PathVariable("tableName") String tableName,
                           @PathVariable("x") Integer x, @PathVariable("y") Integer y, @PathVariable("z") Integer z,
                           HttpServletResponse response) throws IOException {
        Tile tile = tileService.getMvt(tableName, x, y, z);
        response.setContentType("application/x-protobuf");
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        response.setHeader("Access-Control-Max-Age", "1728000");
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Accept-Encoding, Accept-Language, Host, Referer, User-Agent");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        OutputStream os = response.getOutputStream();
        os.write(tile.getImg());
        response.setContentLength(tile.getImg().length);
        os.flush();
        os.close();
    }

}
